<template>
  <div class="update-name">
    <van-nav-bar title="设置昵称"
                 left-text="取消"
                 right-text="完成"
                 @click-left="$emit('close')"
                 @click-right="onConfirm" />
    <div class="field-wrap">
      <van-field v-model.trim="localeName"
                 rows="2"
                 autosize
                 type="textarea"
                 maxlength="50"
                 placeholder="请输入昵称"
                 show-word-limit />
    </div>
  </div>
</template>

<script>
import { updateUserProfile } from '@/api/user'
export default {
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      localeName: this.value
    }
  },
  methods: {
    async onConfirm () {
      this.$toast.loading({
        message: '保存中……',
        forbidClick: true,
        duration: 0
      })
      try {
        if (!this.localeName.length) {
          this.$toast('昵称不能为空')
        }
        await updateUserProfile({
          name: this.localeName
        })
        this.$emit('input', this.localeName)
        this.$emit('close')
        this.$toast('更新成功')
      } catch (err) {
        this.$toast('更新失败')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.field-wrap {
  padding: 20px;
}
</style>
